package com.zyf.heixiang.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zyf.heixiang.common.BaseContext;
import com.zyf.heixiang.common.CustomException;
import com.zyf.heixiang.common.R;
import com.zyf.heixiang.dto.OrdersDto;
import com.zyf.heixiang.entity.OrderDetail;
import com.zyf.heixiang.entity.Orders;
import com.zyf.heixiang.service.OrderDetailService;
import com.zyf.heixiang.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户下单
 *
 * @author 24040
 * @name OrderController
 * @date 2022-08-01 13:54
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 用户下单
     *
     * @param orders
     * @return
     */
    @PostMapping("/submit")

    public R<String> submit(@RequestBody Orders orders) {
        log.info("订单数据:{}", orders.toString());
        orderService.submit(orders);
        return R.success("下单成功");
    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @param ordersDto
     * @return
     */
    @GetMapping("/page")
    @Cacheable(value = "orderCache",
            key = "'orderPage_' + #page + '_' + #pageSize + '_' + #ordersDto.beginTime  + '_' + #ordersDto.endTime + '_' + #ordersDto.getId()",
            unless = "#result.getCode() == 0")
    public R<Page<Orders>> getPage(Integer page, Integer pageSize, OrdersDto ordersDto) {
        //log.info(ordersDto.toString());

        //构建分页查询构造器
        Page<Orders> ordersPage = new Page<Orders>(page, pageSize);
        //编写查询条件
        //select * from orders where (checkout_time BETWEEN ? and ? ) and number =  ?
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(ordersDto.getNumber() != null, Orders::getNumber, ordersDto.getNumber());
        queryWrapper.between(ordersDto.getBeginTime() != null && ordersDto.getEndTime() != null,
                Orders::getCheckoutTime, ordersDto.getBeginTime(), ordersDto.getEndTime());
        //进行分页出查询
        ordersPage = orderService.page(ordersPage, queryWrapper);
        return ordersPage != null ? R.success(ordersPage) : R.error("查询失败");
    }

    /**
     * 更新订单状态
     *
     * @param orders
     * @return 订单状态 1待付款，2待派送，3已派送，4已完成，5已取消
     */
    @PutMapping
    @CacheEvict(value = "orderCache" ,allEntries = true)
    public R<String> order(@RequestBody Orders orders) {
        boolean b = orderService.updateById(orders);
        return b ? R.success("更新成功") : R.error("删除失败");
    }

    /**
     * 根据用户id 查询历史订单/最新订单
//     * @param page
//     * @param pageSize
//     * @param session
//     * @return
     */
//    @GetMapping("/userPage")
//    @Cacheable(value = "orderCache",
//            key = "'userOrderPage_' + #page + '_' + #pageSize + #session.getAttribute('user')",
//            unless = "#result.getCode() == 0")
//    public R<Page<Orders>> userPage(Integer page, Integer pageSize, HttpSession session) {
//        //取出当前用户id
//        Long userId = Long.valueOf(session.getAttribute("user").toString());
//        //构造分页查询器
//        Page<Orders> ordersPage = new Page<Orders>(page, pageSize);
//        //构造sql语句
//        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(Orders::getUserId, userId);
//        queryWrapper.orderByDesc(Orders::getCheckoutTime);
//        //进行查询
//        ordersPage = orderService.page(ordersPage, queryWrapper);
//        return ordersPage != null ? R.success(ordersPage) : R.error("查询失败");
//    }
    @GetMapping("/userPage")
//    @Cacheable(value = "orderCache",
//          key = "'userOrderPage_' + #page + '_' + #pageSize + #session.getAttribute('user')",
//          unless = "#result.getCode() == 0")
    public R<Page> page(int page, int pageSize){
        //分页构造器对象
        Page<Orders> pageInfo = new Page<>(page,pageSize);
        Page<OrdersDto> pageDto = new Page<>(page,pageSize);
        //构造条件查询对象
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getUserId, BaseContext.getCurrentId());
        //这里是直接把当前用户分页的全部结果查询出来，要添加用户id作为查询条件，否则会出现用户可以查询到其他用户的订单情况
        //添加排序条件，根据更新时间降序排列
        queryWrapper.orderByDesc(Orders::getOrderTime);
        //这里是把所有的订单分页查询出来
        orderService.page(pageInfo,queryWrapper);

        //对OrderDto进行属性赋值
        List<Orders> records = pageInfo.getRecords();
        List<OrdersDto> orderDtoList = records.stream().map((item) ->{
            //item其实就是分页查询出来的每个订单对象
            OrdersDto orderDto = new OrdersDto();
            //此时的orderDto对象里面orderDetails属性还是空 下面准备为它赋值
            Long orderId = Long.valueOf(item.getNumber());//获取订单id
            //调用根据订单id条件查询订单明细数据的方法，把查询出来订单明细数据存入orderDetailList
            List<OrderDetail> orderDetailList = orderService.getOrderDetailListByOrderId(orderId);

            BeanUtils.copyProperties(item,orderDto);//把订单对象的数据复制到orderDto中
            //对orderDto进行OrderDetails属性的赋值
            orderDto.setOrderDetails(orderDetailList);
            return orderDto;
        }).collect(Collectors.toList());

        //将订单分页查询的订单数据以外的内容复制到pageDto中，不清楚可以对着图看
        BeanUtils.copyProperties(pageInfo,pageDto,"records");
        pageDto.setRecords(orderDtoList);
        return R.success(pageDto);
    }


    /**
     * 再来一单
     * @return
     */
    @PostMapping("/again")
    @CacheEvict(value = "orderCache" ,allEntries = true)
    public R<String> again(@RequestBody Orders orders, HttpSession session) {
        Long ordersId = orders.getId();
        Long userId = Long.valueOf(session.getAttribute("user").toString());
        boolean flag = orderService.again(ordersId, userId);
        if (!flag) {
            throw new CustomException("操作失败");
        }
        return R.success("操作成功");
    }

    @GetMapping("/orderDetail/{id}")
    public R<List<OrderDetail>> orderDetailR(@PathVariable("id")long id ){
        List<OrderDetail> orderDetails = orderDetailService.selectByOrderId(id);
        return R.success(orderDetails);

    }
}
